<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import ip from '@/utils/baseURL.js';

// 获取当前用户的 session
const session = localStorage.getItem('session');

// 数据列表
const gameRecords = ref([]);
const loading = ref(false);

// 分页配置
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 对话框控制
const dialogVisible = ref(false);
const dialogTitle = ref('');
const isEdit = ref(false);

// 表单数据
const formData = ref({
  id: null,
  session: null, // 届次
  time: '', // 日期，后续会转换为数组格式
  top: '', // 赢家
  topMoney: '', // 赢家资产
  last: '', // 输家
  lastMoney: '', // 输家资产
  remark: '' // 备注
});

// 表单规则
const rules = {
  top: [{ required: true, message: '请输入赢家', trigger: 'blur' }],
  last: [{ required: true, message: '请输入输家', trigger: 'blur' }],
  time: [{ required: true, message: '请选择日期', trigger: 'change' }]
};

// 表单ref
const formRef = ref(null);

// 玩家列表
const players = ['张艺凡', '胡宇浩', '丁玉巍', '杨雨昊', '聂宇豪', '许文燊', '彭然','孙延',"涂佳龙"];

// 获取数据列表
const fetchData = async () => {
  loading.value = true;
  try {
    const response = await axios.get(`${ip}/inter/dfw/getAll`);
    if (response.data.code === 200) {
      gameRecords.value = response.data.data;
      pagination.value.total = response.data.data.length;
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 打开添加对话框
const handleAdd = () => {
  isEdit.value = false;
  dialogTitle.value = '添加记录';
  formData.value = {
    id: null,
    session: gameRecords.value.length + 1,
    time: new Date(),
    top: '',
    topMoney: '',
    last: '',
    lastMoney: '',
    remark: ''
  };
  dialogVisible.value = true;
};

// 打开编辑对话框
const handleEdit = (row) => {
  isEdit.value = true;
  dialogTitle.value = '编辑记录';
  // 将日期数组转换为Date对象
  const timeDate = row.time ? new Date(row.time[0], row.time[1] - 1, row.time[2]) : new Date();
  formData.value = {
    ...row,
    time: timeDate
  };
  dialogVisible.value = true;
};

// 删除记录
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除这条记录吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await axios.delete(`${ip}/inter/dfw/${row.id}`,{headers: { 'Session': `${session}` }});
      
      if (response.data.code === 200) {
        ElMessage.success('删除成功');
        fetchData(); // 刷新数据列表
      } else {
        ElMessage.error(response.data.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      ElMessage.error('删除失败，请重试');
    }
  }).catch(() => {
    // 用户取消删除，不做任何操作
  });
};

// 提交表单
const submitForm = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        // 构造请求数据
        const date = formData.value.time;
        const submitData = {
          session: formData.value.session,
          time: `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`,
          top: formData.value.top,
          topMoney: formData.value.topMoney,
          last: formData.value.last,
          lastMoney: formData.value.lastMoney,
          remark: formData.value.remark || ''
        };

        // 如果是编辑模式，添加id字段
        if (isEdit.value && formData.value.id) {
          submitData.id = formData.value.id;
        }

        // 发送请求
        const response = await axios.post(`${ip}/inter/dfw/saveOrUpdate`, submitData,{headers: { 'Session': `${session}` }});
        
        if (response.data.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '添加成功');
          dialogVisible.value = false;
          fetchData(); // 刷新数据列表
        } else {
          ElMessage.error(response.data.msg || '操作失败');
        }
      } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('提交失败，请重试');
      }
    }
  });
};

onMounted(() => {
  fetchData();
});
</script>


<template>
  <div class="dfw-page">
    <div class="header">
      <h2>大富翁游戏记录管理</h2>
      <el-button type="primary" @click="handleAdd">添加记录</el-button>
    </div>

    <!-- 数据列表 -->
    <el-table :data="gameRecords" style="width: 100%" v-loading="loading" border stripe>
      <el-table-column prop="session" label="届次" width="80" />
      <el-table-column label="日期" width="120">
        <template #default="{ row }">
          {{ row.time ? `${row.time[0]}-${String(row.time[1]).padStart(2, '0')}-${String(row.time[2]).padStart(2, '0')}` : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="top" label="赢家" width="120">
        <template #default="{ row }">
          <span class="winner">{{ row.top }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="topMoney" label="赢家资产" width="120">
        <template #default="{ row }">
          <span class="win-amount">{{ row.topMoney }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="last" label="输家" width="120">
        <template #default="{ row }">
          <span class="loser">{{ row.last }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="lastMoney" label="输家资产" width="120">
        <template #default="{ row }">
          <span class="lose-amount">{{ row.lastMoney }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" min-width="150" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="赢家" prop="top">
          <el-select
            v-model="formData.top"
            placeholder="请选择赢家"
            style="width: 100%"
            filterable
            allow-create
          >
            <el-option
              v-for="player in players"
              :key="player"
              :label="player"
              :value="player"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="赢家资产" prop="topMoney">
          <el-input v-model="formData.topMoney" placeholder="请输入赢家资产" />
        </el-form-item>
        <el-form-item label="输家" prop="last">
          <el-select
            v-model="formData.last"
            placeholder="请选择输家"
            style="width: 100%"
            filterable
            allow-create
          >
            <el-option
              v-for="player in players"
              :key="player"
              :label="player"
              :value="player"
              :disabled="player === formData.top"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="输家资产" prop="lastMoney">
          <el-input v-model="formData.lastMoney" placeholder="请输入输家资产" />
        </el-form-item>
        <el-form-item label="日期" prop="time">
          <el-date-picker
            v-model="formData.time"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>


<style lang="scss" scoped>
.dfw-page {
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
    }
  }

  .winner {
    color: #67C23A;
    font-weight: bold;
  }

  .loser {
    color: #F56C6C;
    font-weight: bold;
  }

  .win-amount {
    color: #67C23A;
    font-weight: bold;
  }

  .lose-amount {
    color: #F56C6C;
    font-weight: bold;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>